package com.ray.database;

import com.alibaba.druid.pool.DruidDataSource;
import com.jfinal.plugin.activerecord.ActiveRecordPlugin;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.jdbc.datasource.TransactionAwareDataSourceProxy;

import java.sql.SQLException;

@Configuration
public class DataSourceConfig {

    @Value("${spring.datasource.main.name}")
    private String main;


    @Bean
    @ConfigurationProperties(prefix = "spring.datasource.main")
    public DruidDataSource mainDatasource() throws SQLException {
        DruidDataSource dataSource = new DruidDataSource();
        dataSource.setFilters("stat");
        return dataSource;
    }


    @Bean
    public ActiveRecordPlugin initMain() throws SQLException {
        ActiveRecordPlugin arp = new ActiveRecordPlugin(main,mainProxy());
        //_MappingKit.mapping(arp);
        arp.start();
        return arp;
    }

    @Bean
    public TransactionAwareDataSourceProxy mainProxy() throws SQLException {
        TransactionAwareDataSourceProxy transactionAwareDataSourceProxy = new TransactionAwareDataSourceProxy();
        transactionAwareDataSourceProxy.setTargetDataSource(mainDatasource());
        return transactionAwareDataSourceProxy;
    }

    @Bean
    @Primary
    public DataSourceTransactionManager mainTransactionManager() throws SQLException {
        DataSourceTransactionManager dataSourceTransactionManager = new DataSourceTransactionManager();
        dataSourceTransactionManager.setDataSource(mainProxy());
        return dataSourceTransactionManager;
    }

}
